package com.dcy.znoa.common.util.excel;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by pengyu on 2017/11/3.
 */
public class ExcelOutput {
    /**
     * 导出excel
     *
     * @param response
     * @param recordList  数据
     * @param keys        键
     * @param columnNames 列名
     * @throws IOException
     */
    public static void ExcelOutput(HttpServletRequest request, HttpServletResponse response, List<Map<String, Object>> recordList, String keys[], String columnNames[], String fileName) throws IOException {
        int index = 0;
        String path = request.getSession().getServletContext().getRealPath("/");
//        String tempFileName = path + "/template/" + fileName + UUID.randomUUID() + "_" + Calendar.getInstance().getTime().getTime() + ".xls";
        String tempFileName = path + "/" + fileName + UUID.randomUUID() + "_" + Calendar.getInstance().getTime().getTime() + ".xls";
        List<Map<String, Object>> tempRecordList;
        ExcelUtil excelUtil = new ExcelUtil();
        XSSFWorkbook workbook;
        //如果没数据创建空表
        if (recordList == null || recordList.size() == 0) {
            workbook = new XSSFWorkbook();
            excelUtil.createSheet(workbook, "default", recordList, keys, columnNames);
            FileOutputStream fos = new FileOutputStream(tempFileName);
            try {
                workbook.write(fos);
            } catch (IOException e) {
                throw e;
            } finally {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
        while (recordList.size() > index) { //用临时文件1000行数据写一次
            int page = recordList.size() < index + 1000 ? recordList.size() : index + 1000;
            tempRecordList = recordList.subList(index, page);
            if (index == 0) {//新建内容
                workbook = new XSSFWorkbook();
                excelUtil.createSheet(workbook, "default", tempRecordList, keys, columnNames);
            } else {//追加内容
                File tempFile = new File(tempFileName);
                workbook = new XSSFWorkbook(new FileInputStream(tempFile));
                excelUtil.appendSheet(workbook, "default", tempRecordList, keys);
            }
            FileOutputStream fos = new FileOutputStream(tempFileName);
            try {
                workbook.write(fos);
            } catch (IOException e) {
                throw e;
            } finally {
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    throw e;
                }
            }
            index += 1000;
        }

        //开始下载文件
        InputStream fis = new BufferedInputStream(new FileInputStream(tempFileName));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=gbk");
        fileName = fileName + ".xlsx";
        String agent= request.getHeader("User-Agent");
        if(!StringUtils.isEmpty(agent)&&agent.contains("Firefox")){
            fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        }else{
            fileName = HttpUtil.urlEncode(fileName,"utf-8");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream out = response.getOutputStream();
        try {
            out.write(buffer);
        } catch (final IOException e) {
            throw e;
        } finally {
            out.flush();
            out.close();
        }
        //最后删除临时文件
        File tempFile = new File(tempFileName);
        if (tempFile.exists()) {
            tempFile.delete();
        }
    }

}
